<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}物品</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          name="uploadfile"
          :action="uploadUrl"
          :headers="getAuthHeaders()"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <!-- 将图片地址赋值到src -->
          <img v-if="model.icon" :src="model.icon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data () {
    return {
      model: {}
    }
  },
  created () {
    // 如果id存在，才执行fetch()方法
    this.id && this.fetch()
  },
  methods: {
    /** 保存 */
    async save () {
      let res
      if (this.id) { // id存在则put修改
        res = await this.$http.put(`rest/items/${this.id}`, this.model)
      } else { // 没有id则新增
        res = await this.$http.post('rest/items', this.model)
      }
      console.log(res)
      this.$router.push('/items/list').catch(err => { console.log(err) })
      this.$message({
        type: 'success',
        message: '保存成功'
      })
    },
    /** 访问页面时获取数据 */
    async fetch () {
      const res = await this.$http.get(`rest/items/${this.id}`)
      console.log(res)
      this.model = res.data
    },
    /** 上传图片后的回调函数 */
    afterUpload (res, uploadfile) {
      console.log('res=>', res)
      console.log('file=>', uploadfile)
      // 为对象添加属性，不具有响应式，使用set将响应式数据加入对象中
      this.$set(this.model, 'icon', res.url)
    }
  }
}
</script>

<style scoped>
</style>
